import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense
from sklearn.model_selection import train_test_split
from matplotlib import pyplot as plt

plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams['axes.unicode_minus'] = False
np.random.seed(1986)

# 导入数据
data_source = pd.read_excel("波士顿房价预测.xlsx")
x = data_source[["人均犯罪率", "住宅用地占比"    , "城镇非住宅用地占比", "虚拟变量", "环保指数", "每栋住宅房间数", "自住单位比例", "据就业中心距离"    , "距高速路便利指数"    , "不动产税率"    , "师生比", "低收入人群占比"]]
y = data_source['房价']

# 拆分训练集和测试集
(train_x, test_x, train_y, test_y) = train_test_split(
    x, y, train_size=0.8, test_size=0.2)

# 创建模型
model = Sequential()
model.add(Dense(units=16, input_dim=x.shape[1], activation='relu'))
model.add(Dense(units=8, activation='relu'))
model.add(Dense(units=1))

# 打印模型信息
model.summary()

# 编译模型
model.compile(loss='mse',
              optimizer='adam',
              metrics=['mae'])

# 训练模型
history = model.fit(train_x, train_y,
          epochs=150, verbose=1)

# 绘制训练过程
plt.plot(history.history["loss"])
plt.title("MSE")
plt.xlabel("epoch")
plt.ylabel("value")
plt.show()

# 评估模型
scores = model.evaluate(train_x, train_y, verbose=0)
print("训练集,%s=%.2f" % (model.metrics_names[1], scores[1]))

scores = model.evaluate(test_x, test_y, verbose=0)
print("测试集,%s=%.2f" % (model.metrics_names[1], scores[1]))

# 预测
predict_x = np.array([[0.00632, 18, 2.31, 0, 0.538, 6.575, 65.2, 4.09, 1, 296, 15.3, 4.98]])
# 类别
print(model.predict(predict_x))

